package com.lh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.entity.table.DepartmentInfo;
import com.lh.mapper.DepartmentInfoMapper;
import com.lh.service.DepartmentService;
import com.lh.utils.Answer;
import com.lh.utils.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    private LogUtil LOG = new LogUtil(DepartmentService.class);

    @Autowired
    private DepartmentInfoMapper departmentInfoMapper;

    @Override
    public Answer<Object> addDepartmentInfo(DepartmentInfo departmentInfo) {
        try {
            String areaCode = departmentInfo.getAreaCode();
            if (StrUtil.isBlank(areaCode)) {
                return Answer.build(HttpServletResponse.SC_BAD_REQUEST, "", "区域编码不能为空");
            }
            String areaName = departmentInfo.getAreaName();
            if (StrUtil.isBlank(areaName)) {
                return Answer.build(HttpServletResponse.SC_BAD_REQUEST, "", "区域名称不能为空");
            }
            String departmentCode = departmentInfo.getDepartmentCode();
            if (StrUtil.isBlank(departmentCode)) {
                return Answer.build(HttpServletResponse.SC_BAD_REQUEST, "", "部门编码不能为空");
            }
            String departmentName = departmentInfo.getDepartmentName();
            if (StrUtil.isBlank(departmentName)) {
                return Answer.build(HttpServletResponse.SC_BAD_REQUEST, "", "部门名称不能为空");
            }

            departmentInfoMapper.insert(departmentInfo);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求addDepartmentInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> updateDepartmentInfo(DepartmentInfo departmentInfo) {
        try {
            Integer id = departmentInfo.getId();
            if (id == null) {
                return Answer.build(HttpServletResponse.SC_BAD_REQUEST, "", "id不能为空");
            }
            departmentInfoMapper.updateById(departmentInfo);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求updateDepartmentInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> deleteDepartmentInfo(DepartmentInfo departmentInfo) {
        try {
            Integer id = departmentInfo.getId();
            if (id == null) {
                return Answer.build(HttpServletResponse.SC_BAD_REQUEST, "", "id不能为空");
            }
            departmentInfoMapper.deleteById(id);
            return Answer.ok("请求成功");
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求deleteDepartmentInfo失败！", e);
        }
    }

    @Override
    public Answer<Object> getDepartmentInfoList(DepartmentInfo departmentInfo) {
        try{
            Integer id = departmentInfo.getId();
            if (id == null) {
                return Answer.build(HttpServletResponse.SC_BAD_REQUEST, "", "id不能为空");
            }
            return Answer.ok(departmentInfoMapper.selectById(id));
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求getDepartmentInfoList失败！", e);
        }
    }

    @Override
    public Answer<Object> getAllDepartment() {
        try {
            List<DepartmentInfo> departmentInfos = departmentInfoMapper.selectList(null);
            List<DepartmentInfo> tree = new ArrayList<>();
            Map<String, DepartmentInfo> map = new HashMap<>();
            // 先将所有节点放入 map 中
            for (DepartmentInfo node : departmentInfos) {
                map.put(node.getDepartmentCode(), node);
            }
            // 构建树形结构
            for (DepartmentInfo node : departmentInfos) {
                String parentCode = node.getParentCode();
                if (parentCode == null || !map.containsKey(parentCode)) {
                    // 根节点
                    tree.add(node);
                } else {
                    // 非根节点，添加到父节点的 children 列表中
                    DepartmentInfo parent = map.get(parentCode);
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
            List<JSONObject> resList = new ArrayList<>();
            for (DepartmentInfo node : tree) {
                JSONObject json = convertToJsonByDepartment(node);
                resList.add(json);
            }
            return Answer.ok(resList);
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求getAllDepartment失败！", e);
        }
    }

    @Override
    public Answer<Object> getDepartmentInfoPage(cn.hutool.json.JSONObject reqJson) {
        try{
            Integer pageNum = reqJson.getInt("pageNum");
            Integer pageSize = reqJson.getInt("pageSize");
            IPage<DepartmentInfo> page = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<DepartmentInfo> departmentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();

            String departmentCode = reqJson.getStr("departmentCode");
            String departmentName = reqJson.getStr("departmentName");
            String parentCode = reqJson.getStr("parentCode");
            String parentName = reqJson.getStr("parentName");
            String areaCode = reqJson.getStr("areaCode");
            if (StrUtil.isNotBlank(departmentCode)) {
                departmentInfoLambdaQueryWrapper.like(DepartmentInfo::getDepartmentCode, departmentCode);
            }
            if (StrUtil.isNotBlank(departmentName)) {
                departmentInfoLambdaQueryWrapper.like(DepartmentInfo::getDepartmentName, departmentName);
            }
            if (StrUtil.isNotBlank(parentCode)) {
                departmentInfoLambdaQueryWrapper.eq(DepartmentInfo::getParentCode, parentCode);
            }
            if (StrUtil.isNotBlank(parentName)) {
                departmentInfoLambdaQueryWrapper.like(DepartmentInfo::getParentName, parentName);
            }
            if (StrUtil.isNotBlank(areaCode)) {
                departmentInfoLambdaQueryWrapper.eq(DepartmentInfo::getAreaCode, areaCode);
            }

            departmentInfoLambdaQueryWrapper.orderByAsc(DepartmentInfo::getId);
            IPage<DepartmentInfo> departmentInfoIPage = departmentInfoMapper.selectPage(page, departmentInfoLambdaQueryWrapper);
            return Answer.ok(departmentInfoIPage);
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求getDepartmentInfoPage失败！", e);
        }
    }

    @Override
    public Answer<Object> getDepartmentChildInfo(DepartmentInfo departmentInfo) {
        try {
            String departmentCode = departmentInfo.getDepartmentCode();
            if (StrUtil.isBlank(departmentCode)) {
                return Answer.build(HttpServletResponse.SC_BAD_REQUEST, "", "departmentCode不能为空");
            }
            LambdaQueryWrapper<DepartmentInfo> departmentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            departmentInfoLambdaQueryWrapper.eq(DepartmentInfo::getParentCode, departmentCode);
            List<DepartmentInfo> departmentInfoList = departmentInfoMapper.selectList(departmentInfoLambdaQueryWrapper);
            return Answer.ok(departmentInfoList);
        } catch (Exception e) {
            return LOG.error(Answer.build(), "请求getDepartmentChildInfo失败！", e);
        }
    }

    private JSONObject convertToJsonByDepartment(DepartmentInfo node) {
        JSONObject json = new JSONObject();
        json.put("departmentCode", node.getDepartmentCode());
        json.put("departmentName", node.getDepartmentName());
        List<DepartmentInfo> children = node.getChildren();
        if (children != null && !children.isEmpty()) {
            List<JSONObject> childrenJson = new ArrayList<>();
            for (DepartmentInfo child : children) {
                childrenJson.add(convertToJsonByDepartment(child));
            }
            json.put("childType", childrenJson);
        }
        return json;
    }
}
